import { constantRouterMap } from '@/router'
const _import = require('@/router/_import_' + process.env.NODE_ENV)
import { childrenRouter } from '@/router/childRouter'
import { ceshiRouter } from '@/router/ceshiRouter'
import { getUserMenu } from '@/api/permission'
import { isExternal } from '@/utils/validate'
import _ from 'lodash'
setTimeout(() => {

}, 500)
/* Layout */
import Layout from '@/views/layout/Layout'
const errRouter = { path: '*', redirect: '/404', hidden: true }
let arrayRouter = []
let dataJson = {}
let itemArr = []
function componentFilter(route) {
  if (typeof route.component === 'string') {
    if (route.component === 'Layout') {
      route.component = Layout
    } else if (route.component === 'productionLayout') {
      route.component = _import('production/layout/productionLayout')
    } else if (route.component === 'chooselibraryLayout') {
      route.component = _import('chooseLibrary/layout/chooseLibraryLayout')
    } else if (route.component === 'cloundlibraryLayout') {
      route.component = _import('cloundLibrary/layout/cloundLibraryLayout')
    } else if (route.component === 'compileLayout') {
      route.component = _import('compile/layout/compileLayout')
    } else if (route.component === 'reviewLayout') {
      route.component = _import('review/layout/reviewLayout')
    } else if (route.component === 'releaseLayout') {
      route.component = _import('release/layout/releaseLayout')
    } else if (route.component === 'subMenuLayout') {
      route.component = _import('systemManage/menuManagement/layout/subMenuLayout')
    } else if (route.component === 'organizationLayout') {
      route.component = _import('systemManage/organizationManagement/layout/organizationLayout')
    } else {
      route.component = _import(route.component)
      // try {
      //   route.component = _import(route.component)
      // } catch (e) {
      //   console.log(e)
      // }
    }
  }
}
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 */
function filterAsyncRouter(asyncRouterMap) {
  const asyncRouterArr = []
  for (var i = 0; i < asyncRouterMap.length; i++) {
    let asyncRouter = asyncRouterMap[i]
    if (asyncRouter.hidden) {
      asyncRouter.meta.hidden = asyncRouter.hidden
    }
    if (asyncRouter.component === 'none') {
      let child = asyncRouter.children.map(r => {
        r.path = JoinPath(asyncRouter.path, r.path)
        return r
      })
      asyncRouterMap.splice(i, 1, ...child)
      i--
      continue
    }
    try {
      componentFilter(asyncRouter)
    } catch (e) {
      console.log(e)
      continue
    }

    var asyncRouterChildren = asyncRouter.children
    if (asyncRouterChildren && asyncRouterChildren.length) {
      try {
        asyncRouterChildren = filterAsyncRouter(asyncRouterChildren)
      } catch (e) {
        continue
      }
      asyncRouter.children = asyncRouterChildren
    } else {
      delete asyncRouter.children
    }
    if (asyncRouter.redirect === null || asyncRouter === '') {
      delete asyncRouter.redirect
    }
    asyncRouterArr.push(asyncRouter)
  }
  return asyncRouterArr
}

/**
 * 处理路由路径
 * @param p1,p2
 */
function JoinPath(p1, p2) {
  // 方法用于检测字符串是否以指定的前缀开始
  if (p2.startsWith('/')) {
    return p2
  }
  // 方法用于检测字符串是否以指定的后缀结束
  if (p1.endsWith('/')) {
    return `${p1}${p2}`
  }
  return `${p1}/${p2}`
}
/**
 * 递归符合用户角色权限的路由表，返回用户菜单
 * @param asyncMenuMap
 */
function filterAsyncMenu(asyncMenuMap, path = '') {
  const asyncMenuArr = []
  for (var routes in asyncMenuMap) {
    var asyncMenu = asyncMenuMap[routes]
    // 首先判断路由是显示还是隐藏，如果是隐藏的话直接跳过循环继续往下走
    if (asyncMenu.hidden) {
      continue
    }
    // try {
    //   componentFilter(asyncMenu)
    // } catch (e) {
    //   console.log(e)
    //   continue
    // }
    // 每一个菜单项的meta值
    var asyncMenuMeta = asyncMenu.meta
    // 菜单项是否设置了 type 为0
    // var asyncMenuMetaType = asyncMenuMeta.type
    if (!isExternal(asyncMenu.path)) {
      asyncMenu.path = JoinPath(path, asyncMenu.path)
    }
    if (true) {
      // 递归深度克隆,每一个路由菜单的子项
      var asyncMenuChildren = _.cloneDeep(asyncMenu.children)
      if (asyncMenuChildren && asyncMenuChildren.length) {
        try {
          asyncMenuChildren = filterAsyncMenu(asyncMenuChildren, asyncMenu.path)
        } catch (e) {
          console.log(e)
          continue
        }
        asyncMenu.children = asyncMenuChildren
      } else {
        delete asyncMenu.children
      }
      if (asyncMenu.redirect === null || asyncMenu === '') {
        delete asyncMenu.redirect
      }
      asyncMenuArr.push(asyncMenu)
    }
  }
  return asyncMenuArr
}

/**
 * 对对象进行深拷贝
 *
 */

function deepClone(obj) {
  var _obj = JSON.stringify(obj)
  var objClone = JSON.parse(_obj)
  return objClone
}

function arrayReconstruction(arrayData) {
  // 循环递归路由，判断菜单是否存在单独展示菜单（路由存在meta属性，meta 对象里面 存在 childrenRouterId 值 即为 当前路由 children 里面存在单独展示的菜单）
  arrayData.forEach((val, index) => {
    if (val.meta !== undefined && val.meta.childrenRouterId) {
      val.children.forEach((valChild, indexChild) => {
        if (valChild.meta !== undefined && valChild.meta.childrenRouter === val.meta.childrenRouterId) {
          itemArr.push(valChild)
        }
      })
      eval('dataJson.' + val.meta.childrenRouterId + '= itemArr')
      itemArr = []
    }
    if (val.children !== undefined && val.children.length > 0) {
      arrayReconstruction(val.children)
    }
  })
}

function routerRemoveItems(routers) {
  let myRouter = routers
  myRouter = myRouter.filter(val => val.meta === undefined || val.meta.childrenRouter === undefined)
  myRouter.forEach(x => x.children && (x.children = routerRemoveItems(x.children)))
  return myRouter
}

function addRouterIndependentFun(routerJson) {
  let objRoutr = []
  for (let key in routerJson) {
    objRoutr = objRoutr.concat(routerJson[key])
  }
  return objRoutr
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    routerJson: [],
    menus: [],
    childrensMenu: [],
    activeMenuIndex: 0,
    menu: [],
    menuLoading: true
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_MENUS: (state, menus) => {
      state.menus[state.activeMenuIndex] = [...menus]
      state.menu = state.menus[state.activeMenuIndex]
    },
    SET_ROUTERJSON: (state, routerJson) => {
      state.routerJson = routerJson
    },
    SET_CHILDRENS_MENUS: (state, childsMenu) => {
      state.childrensMenu = childsMenu
    },
    SET_ACTIVE_MENU_INDEX: (state, index) => {
      state.activeMenuIndex = index
      state.menu = state.menus[state.activeMenuIndex] || []
    },
    SET_ACTIVE_MENU_LOADING: (state, loading) => {
      state.menuLoading = loading
    }
  },
  actions: {
    GenerateRoutes({ commit, state }, type) {
      return new Promise(resolve => {
        let accessedRouters = []
        let accessedMenus = []
        let newRouterArr = []
        let newRouterIndependent = []
        state.menuLoading = true
        getUserMenu(type).then(response => {
          if (response.data.data.length > 0) {
            arrayReconstruction(ceshiRouter) // dataJson - 即为需要单独显示的二级菜单数据
            commit('SET_ROUTERJSON', dataJson)
            const asyncRouterMap = deepClone(response.data.data)
            const asyncMenuMap = deepClone(response.data.data)
            var constantMap = _.cloneDeep(constantRouterMap)
            // 删除路由中需要单独展示的菜单
            newRouterArr = routerRemoveItems(ceshiRouter)
            newRouterIndependent = addRouterIndependentFun(dataJson)
            accessedRouters = filterAsyncRouter(asyncRouterMap)
            // 把处理好的路由添加到menu里面
            accessedMenus = filterAsyncMenu(asyncMenuMap.concat(constantMap, newRouterArr))
            accessedRouters.push(errRouter)
            // 子菜单合并到router
            // commit('SET_ROUTERS', accessedRouters)
            // 把处理好的路由，接口返回路由和路由表路由合并一起添加到 router 中
            commit('SET_ROUTERS', accessedRouters.concat(childrenRouter, newRouterArr, newRouterIndependent)) // 路由
            commit('SET_MENUS', accessedMenus) // 菜单
            commit('SET_CHILDRENS_MENUS', childrenRouter)
            resolve()
          } else {
            // commit('SET_ROUTERS', accessedRouters.concat(childrenRouter))
            commit('SET_ROUTERS', accessedRouters.concat(childrenRouter, newRouterArr, newRouterIndependent))
            commit('SET_MENUS', accessedMenus)
            commit('SET_CHILDRENS_MENUS', childrenRouter)
            resolve()
          }
        })
      })
    },
    async ChangeActiveMenuIndex({ commit, state }, index) {
      console.log(state.menus)
      commit('SET_ACTIVE_MENU_INDEX', index)
      if (state.menus[index] === undefined) {
        return Promise.resolve()
      } else {
        return Promise.reject()
      }
    },
    async ChangeMenuLoading({ commit, state }, loading) {
      commit('SET_ACTIVE_MENU_LOADING', loading)
    }
  }
}

export default permission
